import { createApp } from 'vue'
import mobileLayer from "./mobileLayer.vue";
let defaultOptions = {
    //弹窗打开的组件
    component:'',
    //传入数据
    data:{},
    //父元素的this
    curVm:{},
    //弹窗层级
    zIndex:1000,
    //弹窗关闭时触发
    close:(id)=>{},
    //弹框的样式
    class:'',
    use:{},//main里面的use
    components:{}//main里面的全局注册组件
}

function mergeJson(options, def) {
    for (let key in def) {
        if (!options.hasOwnProperty(key)) {
            options[key] = def[key];
        }
    }
    return options;
}

function createDiv(){
    let _dialog = document.body.querySelector('.yx-mobile-dialog-layer')
    if(!_dialog){
        let _div = document.createElement('div');
        _div.classList.add('yx-mobile-dialog-layer')
        return _div ;
    }else {
        return _dialog
    }
}

const layer = function (app) {
    //注册实例
    defaultOptions['globalApp'] = app ;

    /**
     * 打开弹窗
     * @param options
     * @param callback
     */
    function open(options,callback){
        options.destroy = callback ;
        let _options = mergeJson(options,defaultOptions);
        let random = Math.random().toString(36).slice(-6);
        let id = `yx-mobile-layer-${random}`;

        _options['id'] = id ;
        let divBox = createDiv()
        let curApp = createApp(mobileLayer,{options});
        let _fragment = document.createDocumentFragment()
        let vm = curApp.mount(_fragment)
        divBox.appendChild(_fragment)
        vm.setVm(curApp);
        document.body.appendChild(divBox);
    }
    return {
        open
    }
}

function install (app,option){
    if(!app){ return }
    if(app.config){
        app.config.globalProperties.$layer = layer(app) ;
        defaultOptions.components = option.components || {} ;
        defaultOptions.use = option.use || {} ;
    }
}

export {
    layer
}

export default install
